/* eslint-disable no-negated-condition */
import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {Popconfirm, Table, Button, Form, Row, Col, Card, Spin, Modal, message as msg} from 'antd';
import {getDetail} from './api';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS, DATETIME_FORMAT, FILES_API} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions, uuid} from './utils';
import {conventEnumValueToString, formatDateTime, formatPercent, formatAmount} from '../utils';
import {PERMISSION} from './constants';
import {newOrUpdateOrderValidator, approveValidator} from './validator';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import InputAmount from '../common/InputAmount';
import FileUpload from './FileUpload';
import {currency, marketingActivityFundSource, marketingActivityItemType, marketingActivityJudgeResult} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import WrappedDatePicker from '../common/WrappedDatePicker';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import styles from './style.css';
const {Description} = DescriptionList;
// eslint-disable-next-line prefer-const
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        valiSaleOrder: false,
        data: {
            currency: currency.USD
        },
        marketingActivityDetails: [],
    };

    componentDidMount() {
        this.getDetailInfo();
    }

    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            marketingActivityDetails: res.data.marketingActivityDetails,
                            marketingActivityApprovalRecords: res.data.marketingActivityApprovalRecords
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }

    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    
    // eslint-disable-next-line react/sort-comp
    onClickReturnBtn = () => {
        this.props.onCancel();
    }

    onClickAddDetailBtn = () => {
        const details = this.state.marketingActivityDetails;
        this.setState({
            marketingActivityDetails: [
                ...details,
                {
                    id: uuid(),
                }
            ]
        });
    };
    onSubmit = () => {
        if(this.props.initEnum.brands.length === 1)
            // eslint-disable-next-line react/no-direct-mutation-state
            this.state.data.brandId = this.props.initEnum.brands[0].value;
        const isValid = newOrUpdateOrderValidator(this.state.data, this.state.marketingActivityDetails, this.props.page);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data, this.state.marketingActivityDetails, this.props.page).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitPass = () => {
        const isValid = approveValidator(this.state.data, this.props.page, this.state.marketingActivityDetails);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmitPass(this.state.data, this.props.page, this.state.marketingActivityDetails).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitReject = () => {
        const isValid = approveValidator(this.state.data, this.props.page, this.state.marketingActivityDetails);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmitReject(this.state.data, this.props.page, this.state.marketingActivityDetails).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSelectDealer = (condition = {}) => {
        // if(this.props.initEnum.brands.length === 1)
        //     this.state.data.brandId = this.props.initEnum.brands[0].value;
        // if(!this.state.data.brandId)
        //     msg.warn(this.props.intl.formatMessage({
        //         id: 'NewPanel.message.choseBrand',
        //         defaultMessage: '请先选择品牌'
        //     }));
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                    country: condition.countryName,
                    marketDepartmentName: condition.marketDepartmentName
                }
            };
        });
    };
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onDeleteAll = () => {
        this.setState({
            marketingActivityDetails: [],
            hasOperat: true,
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const tmp = this.state.marketingActivityDetails.filter(d => d.id !== id);
        if(this.state.marketingActivityDetails.length !== 0)
            this.setState({
                marketingActivityDetails: [...tmp],
                hasOperat: true,
            });
    }
    itemOnChange = (item, id) => {
        const details = this.state.marketingActivityDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    item,
                });
            return d;
        });
        this.setState({
            marketingActivityDetails: tmp,
            hasOperat: true
        });
    }
    onUpdateInvestAmount = (investAmount, id) => {
        const details = this.state.marketingActivityDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    investAmount,
                });
            return d;
        });
        this.setState({
            marketingActivityDetails: tmp,
            hasOperat: true
        });
    }
    onUpdateSupportAmount = (supportAmount, id) => {
        const details = this.state.marketingActivityDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    supportAmount,
                });
            return d;
        });
        this.setState({
            marketingActivityDetails: tmp,
            hasOperat: true
        });
    }
    onUpdateFundSource = (fundSource, id) => {
        const details = this.state.marketingActivityDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    fundSource,
                });
            return d;
        });
        this.setState({
            marketingActivityDetails: tmp,
            hasOperat: true
        });
    }
    onUpdateItemType = (itemType, id) => {
        const details = this.state.marketingActivityDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    itemType,
                });
            return d;
        });
        this.setState({
            marketingActivityDetails: tmp,
            hasOperat: true
        });
    }
    remarkOnChange = (remark, id) => {
        const details = this.state.marketingActivityDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    remark,
                });
            return d;
        });
        this.setState({
            marketingActivityDetails: tmp,
            hasOperat: true
        });
    }
    render() {
        const {data, marketingActivityDetails, marketingActivityApprovalRecords} = this.state;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateCurrency = !data.currency && this.state.validate ? 'error' : null;
        const validateName = !data.name && this.state.validate ? 'error' : null;
        const validateApproveComment = !data.approveComment && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        let investAmountSum = 0;
        let supportAmountSum = 0;
        let supportRatioSum = 0;
        if(marketingActivityDetails)
            marketingActivityDetails.forEach(v => {
                investAmountSum += v.investAmount;
                supportAmountSum += v.supportAmount;
                supportRatioSum += (((v.supportAmount ? v.supportAmount : 0) / (v.investAmount ? v.investAmount : 0)) || 0) * 100;
            });

        const columns = [{
            title: (<span>{formatMessage({
                id: 'newPanel.column.item',
                defaultMessage: '项目'
            })}</span>
            ),
            dataIndex: 'item',
            render: (text, record) => {
                const validate = (!text || text === undefined) || text === 0 ? {validateStatus: 'error'} : null;
                return (this.props.page === 'approve' || this.props.page === 'upload' || this.props.page === 'approveReport' || this.props.page === 'approveFee' || this.props.page === 'register') ? text : (<FormItem {...validate}>
                    <TextInput
                        id={record.id}
                        value={record.item}
                        onBlur={this.itemOnChange}/>
                </FormItem>);
            }
        }, {
            title: (<span>{formatMessage({
                id: 'newPanel.column.investAmount',
                defaultMessage: `投入/万${conventEnumValueToString(currency, data.currency)}`
            })}</span>
            ),
            dataIndex: 'investAmount',
            render: (text, record) => {
                const validate = (!text || text === undefined) || text === 0 ? {validateStatus: 'error'} : null;
                return (this.props.page === 'approve' || this.props.page === 'upload' || this.props.page === 'approveReport' || this.props.page === 'approveFee' || this.props.page === 'register') ? formatAmount(text) : (<FormItem {...validate}>
                    <InputAmount
                        id={record.id}
                        value={text}
                        onChange={this.onUpdateInvestAmount}/>
                </FormItem>);
            }
        }, {
            title: (<span>{formatMessage({
                id: 'newPanel.column.supportAmount',
                defaultMessage: `支持/万${conventEnumValueToString(currency, data.currency)}`
            })}</span>
            ),
            dataIndex: 'supportAmount',
            render: (text, record) => {
                const validate = (!text || text === undefined) || text === 0 ? {validateStatus: 'error'} : null;
                return (this.props.page === 'approve' || this.props.page === 'upload' || this.props.page === 'approveReport' || this.props.page === 'approveFee' || this.props.page === 'register') ? formatAmount(text) : (<FormItem {...validate}>
                    <InputAmount
                        id={record.id}
                        value={text}
                        onChange={this.onUpdateSupportAmount}/>
                </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.supportRatio',
                defaultMessage: '支持比例'
            }),
            dataIndex: 'supportRatio',
            render: (text, record) => formatPercent((((record.supportAmount ? record.supportAmount : 0) / (record.investAmount ? record.investAmount : 0)) || 0) * 100)
        }, {
            title: formatMessage({
                id: 'newPanel.column.fundSource',
                defaultMessage: '资金来源'
            }),
            dataIndex: 'fundSource',
            width: 200,
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                return (this.props.page === 'approve' || this.props.page === 'upload' || this.props.page === 'approveReport' || this.props.page === 'approveFee' || this.props.page === 'register') ? conventEnumValueToString(marketingActivityFundSource, text) : (<FormItem {...validate}>
                    <WrappedSelect
                        allowClear
                        id={record.id}
                        value={text}
                        options={marketingActivityFundSource.toList(language)}
                        onChange={this.onUpdateFundSource}/>
                </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.itemType',
                defaultMessage: '项目类型'
            }),
            dataIndex: 'itemType',
            width: 200,
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                return (this.props.page === 'approve' || this.props.page === 'upload' || this.props.page === 'approveReport' || this.props.page === 'approveFee' || this.props.page === 'register') ? conventEnumValueToString(marketingActivityItemType, text) : (<FormItem {...validate}>
                    <WrappedSelect
                        allowClear
                        id={record.id}
                        value={text}
                        options={marketingActivityItemType.toList(language)}
                        onChange={this.onUpdateItemType}/>
                </FormItem>);
            }
        }, {
            title: (<span>{formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            })}</span>
            ),
            dataIndex: 'remark',
            render: (text, record) => this.props.page === 'approve' ? text : (<FormItem>
                <TextInput
                    id={record.id}
                    value={record.remark}
                    onBlur={this.remarkOnChange}/>
            </FormItem>)
        }];
        if(this.props.page === 'add')
            columns.push({
                title: marketingActivityDetails.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'newPanel.validation.isDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onDeleteAll} >
                            <a>{formatMessage({
                                id: 'newPanel.validation.clear',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : null,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                    id: 'newPanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>
            });
        const columnResults = [{
            title: formatMessage({
                id: 'newPanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
            render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(marketingActivityJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation'
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                {this.props.initEnum.brands.length !== 1 &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        {!this.props.id ? <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.initEnum.brands}
                                            onChange={this.handleFilterChange}/>
                                            : `(${data.brandCode})${data.brandName}`}
                                    </FormItem>
                                </Col>
                                }
                                {this.props.id &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.code',
                                            defaultMessage: '活动编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.name',
                                            defaultMessage: '活动名称'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateName} required>
                                        {this.props.page === 'add' && <TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.handleFilterChange} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        {!this.props.id ? <DealerSelectPanel
                                            disabled={this.props.id}
                                            value={dealerInfo}
                                            onChange={this.handleFilterChange}
                                            onSelect={this.onSelectDealer} />
                                            : `(${data.dealerCode})${data.dealerName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.country',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.formC.marketDepartmentName',
                                            defaultMessage: '大区'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.marketDepartmentName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.formC.totalInvestAmount',
                                            defaultMessage: `总投入/万${conventEnumValueToString(currency, data.currency)}`
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(investAmountSum ? investAmountSum : null)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.formC.totalSupportAmount',
                                            defaultMessage: `总支持/万${conventEnumValueToString(currency, data.currency)}`
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(supportAmountSum ? supportAmountSum : null)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.formC.totalSupportRatio',
                                            defaultMessage: '支持总比例'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatPercent(supportRatioSum ? supportRatioSum : null)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required>
                                        {this.props.page === 'add' && <WrappedSelect
                                            allowClear
                                            name="currency"
                                            value={data.currency}
                                            options={currency.toList(language)}
                                            onChange={this.handleFilterChange}/>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.startDate',
                                            defaultMessage: '活动开始日期'
                                        })} {...FORM_OPTIONS.item}>
                                        {this.props.page === 'add' && <WrappedDatePicker
                                            name="startDate"
                                            value={data.startDate}
                                            onChange={this.handleFilterChange} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.endDate',
                                            defaultMessage: '活动结束日期'
                                        })} {...FORM_OPTIONS.item}>
                                        {this.props.page === 'add' && <WrappedDatePicker
                                            name="endDate"
                                            value={data.endDate}
                                            onChange={this.handleFilterChange} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'newPanel.marketingActivityDetails',
                                defaultMessage: '市场营销活动信息清单'
                            })}>
                            {this.props.page === 'add' && <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newDetail',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            }
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={marketingActivityDetails}
                                {...TABLE} />
                        </Card>
                        {this.props.id && <Card
                            title={formatMessage({
                                id: 'newPanel.marketingActivityApprovalRecords',
                                defaultMessage: '市场营销活动审核结果清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columnResults}
                                rowKey="id"
                                pagination={false}
                                dataSource={marketingActivityApprovalRecords}
                                {...TABLE} />
                        </Card>}
                        {(this.props.page === 'add' || this.props.page === 'upload' || this.props.page === 'register') ? <Card title={formatMessage({
                            id: 'newPanel.title.files',
                            defaultMessage: '附件清单'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload}
                                        onRemove={this.removeFilePath}
                                        fileList={data.attachments || []}/>
                                </Col>
                            </Row>
                        </Card>
                            : <Card>
                                {data.attachments && data.attachments.length >= 0
                                    ? <DescriptionList size="large" title={formatMessage({
                                        id: 'newPanel.card.attachment',
                                        defaultMessage: '附件清单'
                                    })}>
                                        {data.attachments.map(item => (<Description key={item.fileId}>
                                            <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                                {item.fileName}</a></Description>))}
                                    </DescriptionList>
                                    : <DescriptionList title={formatMessage({
                                        id: 'newPanel.content.noAttachment',
                                        defaultMessage: '暂无附件'
                                    })}>
                                    </DescriptionList>}
                            </Card>}
                        {(this.props.page === 'approve' || this.props.page === 'approveReport' || this.props.page === 'approveFee') && <Card
                            title={formatMessage({
                                id: 'newPanel.approve',
                                defaultMessage: '审核区域'
                            })}>
                            <Row>
                                <Col {...FORM_ROW_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.approveComment',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateApproveComment} required>
                                        <TextInput type="textarea"
                                            name="approveComment"
                                            value={data.approveComment}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>}
                        <Card type="inner">
                            <Row>
                                {(this.props.page === 'approve' || this.props.page === 'approveReport' || this.props.page === 'approveFee') ? <Col disabled={!submitable} className="col-align-right">
                                    {<Button key="submitPass" loading={this.state.loading}
                                        onClick={this.onSubmitReject}>{formatMessage({
                                            id: 'newPanel.btn.submitPass',
                                            defaultMessage: '审核不通过'
                                        })}</Button>}
                                    <Button key="submitReject" loading={this.state.loading}
                                        onClick={this.onSubmitPass} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submitReject',
                                            defaultMessage: '审核通过'
                                        })}</Button>
                                </Col> : <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                                }
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
    onApprove,
    onReject
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: (data, details, page) => dispatch(onSubmit(data, details, page)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onSubmitPass: (data, page, details) => dispatch(onApprove(data, page, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onSubmitReject: (data, page, details) => dispatch(onReject(data, page, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
